/** 
  实习评价指标设置
*/
<template>
  <div>
    <el-card shadow="never" body-style="padding: 24px;" class="condition-card">
      <el-form label-position="right" label-suffix="：" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="3" style="line-height: 33px;">
            <span class="condition-title">{{ $t("message.filterCondition") }}</span>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('internEvaluateIndexSet.internEvalTemp')">
              <el-select v-model="queryForm.condition.templateId" :disabled="disabledToEditTemp" @change="changeTemplate" clearable style="width: 100%">
                <el-option
                  v-for="item in options.templateId"
                  :key="item.id"
                  :label="item.templateName"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-form-item>
          </el-col>
          <div style="float: right;margin-right: 10px;">
            <el-button @click="reset">{{ $t('message.reset') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{$t('message.filter')}}</el-button>
          </div>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{ $t('internEvaluateIndexSet.internEvalIndexSetList') }}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-right" style="display: flex;">
          <el-button v-if="permitToEdit" @click="editInternEvalIndex">{{ $t('common.btn.edit') }}</el-button>
          <el-button v-if="permitToSave && editModel" @click="saveInternEvalIndex">{{$t('common.btn.save')}}</el-button>
          <el-button v-if="permitToAddRow && editModel" type="primary" @click="addLine">{{$t('graduateBase.addLine')}}</el-button>
          <el-button v-if="permitToDeleteRow && editModel" type="danger" @click="delLine">{{$t('graduateBase.deleteLine')}}</el-button>
        </div>
      </div>
      <el-form :model="internEvalIndexTable" ref="internEvalIndexTable" :rules="rulesForm">
        <edu-table :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="internEvalIndexTable.dataList" size="mini" @selection-change="handleSelectionChange">
          <edu-table-column :label="$t('internEvaluateIndexSet.internEvalIndex')" prop="itemName">
            <template slot-scope="scope">
              <el-form-item v-if="editModel" style="margin-top: 15px;" :prop="'dataList.' + scope.$index + '.itemName'" label-width="0" :rules="rulesForm.itemName">
                <el-input v-model.trim="scope.row.itemName" :maxlength="64" clearable></el-input>
              </el-form-item>
              <div v-else>{{ scope.row.itemName }}</div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('internEvaluateIndexSet.evalIndexDes')" prop="description">
            <template slot-scope="scope">
              <el-form-item v-if="editModel" style="margin-top: 15px;" :prop="'dataList.' + scope.$index + '.description'" label-width="0" :rules="rulesForm.description">
                <el-input v-model.trim="scope.row.description" :maxlength="512" clearable></el-input>
              </el-form-item>
              <div v-else>{{ scope.row.description }}</div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('internEvaluateIndexSet.evalIndexWeig')" prop="weight">
            <template slot-scope="scope">
              <el-form-item v-if="editModel" style="margin-top: 15px;" :prop="'dataList.' + scope.$index + '.weight'" label-width="0" :rules="rulesForm.weight">
                <el-input v-model.trim="scope.row.weight" clearable></el-input>
              </el-form-item>
              <div v-else>{{ scope.row.weight }}</div>
            </template>
          </edu-table-column>
          <edu-table-column v-if="!editModel" :label="$t('common.text.operation')" fit prop="operate">
            <template slot-scope="props">
              <el-button v-if="permitToDetail" type="text" @click="selectDetails(props.row)">{{$t('graduate.details')}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
      </el-form>
      <!-- <el-row type="flex" class="row-bg" justify="end">
        <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
        </el-col>
      </el-row> -->
    </el-card>
    <el-dialog
      @close="closeAssessIndexDetails"
      :title="title"
      width="90%"
      :visible.sync="assessIndexDetVisible">
      <intern-eval-index-detail :currentInternEvalIndex="currentInternEvalIndex" :currentInternEvalTemplate="currentInternEvalTemplate"></intern-eval-index-detail>
    </el-dialog>
  </div>
</template>
<script>
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
import internEvalIndexDetail from './internEvalIndexDetail';
export default {
  components: {
    'intern-eval-index-detail': internEvalIndexDetail
  },
  data () {
    return {
      auths: [],
      permitToEdit: false,
      permitToSave: false,
      permitToAddRow: false,
      permitToDeleteRow: false,
      permitToDetail: false,
      deleteInfo: [],
      currentInternEvalTemplate: {},
      queryForm: {
        pageNum_: 1,
        pageSize_: 99999,
        total_: 0,
        condition: {
          "templateId": "",
          "itemCategory": "2"
        }
      },
      internEvalIndexTable: {
        dataList: []
      },
      editModel: false,
      indexKey: '1', // 面包屑
      title: '',
      assessIndexDetVisible: false,
      multipleSelection: [],
      currentInternEvalIndex: {},
      options: {
        templateId: []
      },
      rulesForm: {
        itemName: [
          { required: true, message: this.$t('internEvaluateIndexSet.requireInternEvalIndex'), trigger: 'blur' },
          { validator: this.checkSpecial, trigger: 'blur'}
        ],
        description: [
          { required: true, message: this.$t('internEvaluateIndexSet.requireEvalIndexDes'), trigger: 'blur' },
          { validator: this.checkSpecial, trigger: 'blur'}
        ],
        weight: [
          {
            validator: this.validateWeight,
            trigger: 'blur'
          }
        ]
      },
      disabledToEditTemp: false
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
    graduateStudentApi.queryInternEvalList({
      "pageNum_": "1",
      "pageSize_": "0",
      "condition": {
        templateName: '',
        trainingLevelList: [],
        trainingTypeList: [],
        degreeTypeList: [],
        learnFormList: [],
        collegeAcademyList: [],
        majorList: [],
        isEnabled: 1
      }
    }).then(res => {
      this.options.templateId = res.data.list;
    });
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')));
      } else {
        callback();
      }
    },
    // 校验考核指标权重
    validateWeight(rule, value, callback) {
      let expReg = /^(\d{1})(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error(this.$t('internEvaluateIndexSet.requireEvalIndexWeig')));
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('asesmentSetting.validateAssessIndexWeig')));
      } else if (Number(value) === 0 || Number(value) > 1) {
        callback(new Error(this.$t('asesmentSetting.validateAssessIndexWeig')));
      } else {
        callback();
      }
    },
    // 切换考核模板
    changeTemplate(val) {
      this.currentInternEvalTemplate = this.options.templateId.find((item) => {
        return item.id === val;
      })
    },
    // 编辑
    editInternEvalIndex() {
      if (!this.queryForm.condition.templateId) {
        this.$message.info(this.$t('internEvaluateIndexSet.mustChooseInternEval'));
        return;
      }
      this.editModel = !this.editModel;
      this.onSubmit();
    },
    // 保存考核指标设置
    saveInternEvalIndex() {
      this.$refs['internEvalIndexTable'].validate((valid) => {
        if (valid) {
          this.internEvalIndexTable.dataList.map((item) => {
            item['itemCategory'] = '2';
            item['deleteFlag'] = '0';
          });
          let currentDeleteInfo = JSON.parse(JSON.stringify(this.deleteInfo));
          if (currentDeleteInfo.length > 0) {
            currentDeleteInfo.map(item => {
              item['itemCategory'] = '2';
              item['deleteFlag'] = '1';
            });
          }
          graduateStudentApi.saveInternEvalIndex({
            "templateId": this.queryForm.condition.templateId,
            "itemCategory": '2',
            "itemList": this.internEvalIndexTable.dataList.concat(currentDeleteInfo)
          }).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('graduateBase.savedSuccessfully'));
              this.editModel = false;
              this.onSubmit();
            }
          });
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      });
    },
    // 新增行
    addLine() {
      this.internEvalIndexTable.dataList.push({
        "uniqueId": new Date().getTime(),
        "templateId": this.queryForm.condition.templateId,
        "itemName": "",
        "description": "",
        "weight": "",
        "itemCategory": "2",
        "deleteFlag": "0"
      });
    },
    // 删除行
    delLine() {
      let _this = this;
      if (this.multipleSelection.length > 0) {
        this.$delConfirm().then(_ => {
          this.deleteInfo = this.multipleSelection;
          for (let i = _this.internEvalIndexTable.dataList.length - 1; i >= 0; i--) {
            _this.multipleSelection.map((element) => {
              if (_this.internEvalIndexTable.dataList[i]) {
                if ((_this.internEvalIndexTable.dataList[i].id && _this.internEvalIndexTable.dataList[i].id === element.id) || (_this.internEvalIndexTable.dataList[i].uniqueId && _this.internEvalIndexTable.dataList[i].uniqueId === element.uniqueId)) {
                  _this.internEvalIndexTable.dataList.splice(i, 1);
                }
              }
            });
          }
          this.$message(this.$t('graduateBase.shouldSave'));
        }).catch(_ => {
        });
      } else {
        this.$message(this.$t('graduateBase.pleaseChoose'));
      }
    },
    reset() {
      this.editModel = false;
      this.queryForm.condition.templateId = '';
      this.internEvalIndexTable.dataList = [];
      this.deleteInfo = [];
      this.queryForm.total_ = 0;
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    getListData() {
      this.deleteInfo = [];
      if (!this.queryForm.condition.templateId) {
        this.$message.info(this.$t('internEvaluateIndexSet.mustChooseInternEval'));
        return;
      }
      graduateStudentApi.queryInternEvalIndexSetList({
        "pageNum_": this.queryForm.pageNum_,
        "pageSize_": this.queryForm.pageSize_,
        "condition": {
          "templateId": this.queryForm.condition.templateId,
          "itemCategory": '2'
        }
      }).then((res) => {
        this.internEvalIndexTable.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 查看详情
    selectDetails(row) {
      this.title = this.$t('internEvaluateIndexSet.evalDetailSet');
      this.currentInternEvalIndex = row;
      this.assessIndexDetVisible = true;
    },
    // 关闭弹框
    closeAssessIndexDetails() {
      this.assessIndexDetVisible = false;
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-internEvalIndexSet-edit') {
              this.permitToEdit = true;
            }
            if (item.authCode === 'graduateStu-internEvalIndexSet-save') {
              this.permitToSave = true;
            }
            if (item.authCode === 'graduateStu-internEvalIndexSet-newLine') {
              this.permitToAddRow = true;
            }
            if (item.authCode === 'graduateStu-internEvalIndexSet-deleteRow') {
              this.permitToDeleteRow = true;
            }
            if (item.authCode === 'graduateStu-internEvalIndexSet-details') {
              this.permitToDetail = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    },
    editModel(newVal) {
      this.disabledToEditTemp = newVal;
    }
  }
}
</script>
<style lang="scss" scoped>
  .condition-card  ::v-deep{
    .el-row {
      height: 30px!important;
    }
    .el-form-item {
      margin-bottom: 0!important;
    }
  }
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }
</style>
